<template>
  <common-layout>
    <template #header>
      管理后台
    </template>

    <template #main>
      <div class="main-content">
        <el-alert
          v-if="alertMessage"
          :title="alertMessage"
          type="success"
          @close="alertMessage = ''"
          :closable="true"
        ></el-alert>

        <el-table :data="users" style="width: 100%">
          <el-table-column prop="id" label="ID" />
          <el-table-column prop="userName" label="用户名" />
          <el-table-column prop="email" label="邮箱" />
          <el-table-column prop="phone" label="手机" />
          <el-table-column prop="roleId" label="角色" :formatter="roleFormatter" />
          <el-table-column label="操作">
            <template v-slot="scope">
              <el-button @click="openPopup(scope.row)">编辑</el-button>
              <el-button @click="confirmDeleteUser(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 简单弹出窗口 -->
        <el-dialog
          v-model="popupVisible"
          title="编辑用户"
          width="30%"
          center
        >
          <edit-user
            :user="selectedUser"
            @submit="handleUserSubmit"
            @close="closePopup"
          />
        </el-dialog>
      </div>
    </template>
  </common-layout>
</template>

<script>
import axios from '../../axios/axios';
import CommonLayout from '../Component/ManagePage.vue';
import EditUser from '../Component/EditUser.vue'; // 导入 EditUser 组件

export default {
  components: {
    CommonLayout,
    EditUser, // 注册 EditUser 组件
  },
  data() {
    return {
      users: [],
      popupVisible: false,
      selectedUser: {}, // 存储选择的用户信息
      alertMessage: '',
    };
  },
  methods: {
    async fetchUsers() {
      try {
        const response = await axios.get('/admin/user');
        this.users = response.map(user => ({
          ...user,
          roleId: this.getRoleText(user.roleId) // 映射角色ID为角色文本
        })); 
      } catch (error) {
        this.handleError('获取用户失败', error);
      }
    },

    // 根据 roleId 返回对应角色名
    getRoleText(roleId) {
      switch (roleId) {
        case 0:
          return '超级管理员';
        case 1:
          return '管理员';
        case 2:
          return '创作者';
          case 3:
            return '普通用户';
        default:
          return '未知角色';
      }
    },

    openPopup(user) {
      this.selectedUser = user; // 存储选择的用户信息
      this.popupVisible = true; // 打开弹出窗口
    },

    closePopup() {
      this.popupVisible = false; // 关闭弹出窗口
    },

    async handleUserSubmit(updatedUser) {
      try {
        // 发送到新的接口，并确保包含用户的 ID
        const response = await axios.post('/admin/user/add', {
          id: updatedUser.id, // 确保传递用户的 ID
          userName: updatedUser.userName,
          email: updatedUser.email,
          phone: updatedUser.phone,
          roleId: updatedUser.roleId,
        });

        // 直接根据返回的布尔值处理
        if (response) {
          this.alertMessage = '用户更新成功';
          await this.fetchUsers(); // 更新列表数据
        } else {
          this.alertMessage = '用户更新失败';
        }
      } catch (error) {
        this.handleError('更新用户失败', error);
      } finally {
        this.closePopup(); // 关闭弹出窗口
      }
    },

    async confirmDeleteUser(user) {
      this.$confirm(`确定要删除用户 ${user.userName} 吗?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteUser(user);
      }).catch(() => {
        this.alertMessage = '删除已取消';
      });
    },

    async deleteUser(user) {
      try {
        const response = await axios.delete(`/admin/user/${user.id}`);
        this.alertMessage = response ? '删除成功' : '删除失败';
        await this.fetchUsers();
      } catch (error) {
        this.handleError('删除用户失败', error);
      }
    },

    handleError(message, error) {
      console.error(message, error);
      this.alertMessage = `${message}，请稍后重试`;
    },
  },
  mounted() {
    this.fetchUsers();
  },
};
</script>

<style>
.main-content {
  padding: 10px;
  overflow-y: auto;
}

.el-table {
  width: 100%;
}

/* 移除可能影响对话框的样式 */
.el-dialog__body {
  padding: 20px;
}

.dialog-footer {
  text-align: right;
}
</style>
